package com.bsoft.messengerserver;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.socks.library.KLog;

/**
 * Created by 泅渡者
 * Created on 2017/9/22.
 */

public class MessengerService extends Service {

    private static final int FLAG = 0x110;

    private Messenger messenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(Message msgfromClient) {
            Message messageToClient = Message.obtain(msgfromClient);
            switch (msgfromClient.what) {
                case FLAG:
                    KLog.d("服务端接收导数据"+msgfromClient.arg1+"&&"+msgfromClient.arg2);
                    messageToClient.what = FLAG;
                    try {
                        //模拟耗时
                        Thread.sleep(2000);
                        messageToClient.arg2 = msgfromClient.arg1 + msgfromClient.arg2;
                        msgfromClient.replyTo.send(messageToClient);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    });

    @Override
    public void onCreate() {
        super.onCreate();
        KLog.d("执行");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        KLog.d("执行");
        return messenger.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        KLog.d("执行");
        return super.onUnbind(intent);
    }
}
